package com.zmj.sy.mom.srv.aps.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmj.sy.mom.srv.aps.bean.bo.test.TestValidCount;
import com.zmj.sy.mom.srv.aps.bean.dto.wms.MesPicking;
import com.zmj.sy.mom.srv.aps.bean.entity.base.BaseEntity;
import com.zmj.sy.mom.srv.aps.bean.entity.base.PhaseJob;
import com.zmj.sy.mom.srv.aps.bean.entity.base.PhaseJobRef;
import com.zmj.sy.mom.srv.aps.bean.entity.mes.Part;
import com.zmj.sy.mom.srv.aps.bean.entity.mes.WorkDetailTask;
import com.zmj.sy.mom.srv.aps.bean.entity.mes.WorkRecord;
import com.zmj.sy.mom.srv.aps.bean.entity.nest.*;
import com.zmj.sy.mom.srv.aps.bean.entity.order.ApsWorkDetail;
import com.zmj.sy.mom.srv.aps.bean.entity.order.ApsWorkOrder;
import com.zmj.sy.mom.srv.aps.bean.entity.order.Order;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.*;
import com.zmj.sy.mom.srv.aps.bean.entity.third.SinoCamPushPlan;
import com.zmj.sy.mom.srv.aps.bean.entity.third.SinoCamReceiveNestPart;
import com.zmj.sy.mom.srv.aps.bean.entity.third.SinoCamReceiveNestPlate;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BaseIdReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BaseResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.base.Result;
import com.zmj.sy.mom.srv.aps.bean.vo.base.SearchParam;
import com.zmj.sy.mom.srv.aps.bean.vo.nest.andon.SendApsMsgDto;
import com.zmj.sy.mom.srv.aps.bean.vo.nest.andon.SendCardMsgDto;
import com.zmj.sy.mom.srv.aps.bean.vo.plate.UpdateNxolpstatusVo;
import com.zmj.sy.mom.srv.aps.bean.vo.test.FalsifyingDataReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.test.TestTableReqVo;
import com.zmj.sy.mom.srv.aps.feign.MomAndonFeign;
import com.zmj.sy.mom.srv.aps.feign.WmsApiClient;
import com.zmj.sy.mom.srv.aps.feign.WmsLtkApiClient;
import com.zmj.sy.mom.srv.aps.mapper.*;
import com.zmj.sy.mom.srv.aps.utils.*;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class TestService {

    private final SpanMapper spanMapper;
    private final GroupMapper groupMapper;
    private final StationMapper stationMapper;
//    private final StationGroupMapper stationGroupMapper;
    private final PositionMapper positionMapper;
    private final ApsWorkOrderMapper apsWorkOrderMapper;
    private final OrderMapper orderMapper;
    private final PhaseMapper phaseMapper;
    private final PhaseJobMapper phaseJobMapper;
    private final PhaseJobRefMapper phaseJobRefMapper;
    private final NestSpaceMapper nestSpaceMapper;
    private final ApsOrderMapper apsOrderMapper;
    private final WmsApiClient wmsApiClient;
    private final WmsLtkApiClient wmsLtkApiClient;
    private final ApsWorkDetailMapper apsWorkDetailMapper;
    private final WorkDetailTaskMapper workDetailTaskMapper;
    private final PartMapper partMapper;
    private final SinoCamReceiveNestPartMapper sinoCamReceiveNestPartMapper;
    private final SinoCamReceiveNestPlateMapper sinoCamReceiveNestPlateMapper;
    private final PlateService plateService;
    private final SinoCamService sinoCamService;
    private final NestReceiveNestMapper nestReceiveNestMapper;
    private final NestReceivePlateMapper nestReceivePlateMapper;
    private final NestReceivePartMapper nestReceivePartMapper;
    private final NestReceiveExcessMapper nestReceiveExcessMapper;
    private final NestReceiveMoveMapper nestReceiveMoveMapper;
    private final WorkRecordMapper workRecordMapper;
    private final SinoCamPushPlanMapper sinoCamPushPlanMapper;
    private final PlatePhaseMapper platePhaseMapper;
    private final PlateMapper plateMapper;
    private final WmsPlatePickMapper wmsPlatePickMapper;
    private final DictTypeMapper dictTypeMapper;
    private final DictDataMapper dictDataMapper;
    private final MomAndonFeign momAndonFeign;

    @Transactional
    public void initSpan(List<String> lines) {
        for (String line : lines) {
            String[] split = line.split("\\t");
            Span span = new Span();
            span.setName(split[0]);
            span.setMyCode(split[1]);
            span.setSeq(Integer.parseInt(split[2]));
            spanMapper.insert(span);
        }

    }

    @Transactional
    public void initGroup(List<String> lines) {
        for (String line : lines) {
            String[] split = line.split("\\t");
            Group one = groupMapper.lambdaQuery().eq(Group::getMyCode, split[2]).one();
            log.info(JsonUtils.toJsonString(one));

            if(one == null){
                Group group = new Group();
                group.setName(split[1]);
                group.setSpanCode(split[0]);
                group.setSpanId(spanMapper.lambdaQuery().eq(Span::getMyCode, split[0]).one().getId());
                group.setMyCode(split[2]);
                groupMapper.insert(group);
            } else {
                one.setName(split[1]);
                one.setSpanCode(split[0]);
                one.setSpanId(spanMapper.lambdaQuery().eq(Span::getMyCode, split[0]).one().getId());
                groupMapper.updateById(one);

            }

        }

    }

    @Transactional
    public void initStation(List<String> lines) {
        for (String line : lines) {
            String[] split = line.split("\\t");
            Group group = groupMapper.lambdaQuery().eq(Group::getMyCode, split[0]).one();
            if(group == null){
                continue;
            }

            Station station = stationMapper.lambdaQuery().eq(Station::getMyCode, split[1]).one();
            if(station == null){
                station = new Station();
                station.setMyCode(split[1]);
                stationMapper.insert(station);
            }

//            StationGroup stationGroup = stationGroupMapper.lambdaQuery()
//                    .eq(StationGroup::getStationId, station.getId())
//                    .eq(StationGroup::getGroupId, group.getId())
//                    .one();

//            if(stationGroup == null){
//                StationGroup sg = new StationGroup();
//                sg.setStationId(station.getId());
//                sg.setGroupId(group.getId());
//                sg.setDefaultGroup(1);
//                stationGroupMapper.insert(sg);
//            }


        }
    }

    @Transactional
    public void initPosition(List<String> lines) {
        Map<String, Integer> stringIntegerMap = MapUtil.of(Pair.of("1", 1), Pair.of("2", 2), Pair.of("7", 7), Pair.of("14", 14));
        for (String line : lines) {
            String[] split = line.split("\\t");

            Station station = stationMapper.lambdaQuery().eq(Station::getMyCode, split[1]).one();
            if(station == null){
//                throw SyExceptionUtils.e("工位不存在:{}", split[0]);
                continue;
            }

            Position position = positionMapper.lambdaQuery()
                    .eq(Position::getStationId, station.getId())
                    .eq(Position::getMyCode, split[3])
                    .one();

            if(position != null){
                continue;
            }

            Position p = new Position();
            p.setType(stringIntegerMap.get(split[0]));
            p.setContainerType(1);
            p.setMyCode(split[3]);
            p.setName(split[2]);
            p.setStationId(station.getId());
            positionMapper.insert(p);

        }

    }

    @Transactional(readOnly = true)
    public void validCount(Integer orderId) {
        List<TestValidCount> allPhaseCount = apsWorkOrderMapper.findAllPhaseCount(orderId);
        Map<Integer, List<TestValidCount>> collect = allPhaseCount.stream().collect(Collectors.groupingBy(TestValidCount::getApsWorkOrderId));

        List<TestValidCount> errorList = new ArrayList<>();
        for (Map.Entry<Integer, List<TestValidCount>> integerListEntry : collect.entrySet()) {
            List<TestValidCount> value = integerListEntry.getValue();

            TestValidCount max = integerListEntry.getValue().stream().max(Comparator.comparing(TestValidCount::getFinishCount)).get();
            value.sort(Comparator.comparing(TestValidCount::getPhaseSeq));

            for (TestValidCount current : value) {
                if(current.getPhaseSeq().compareTo(max.getPhaseSeq()) < 0 && current.getFinishCount().compareTo(max.getFinishCount()) > 0){
                    errorList.add(current);
                    current.setType(String.format("%s工序完成数量%d大于%s工序完成数量%d", current.getPhaseCode(), current.getFinishCount(), max.getPhaseCode(), max.getFinishCount()));
                }

                if(current.getTotalCount().compareTo(current.getOrderCount()) > 0 || current.getFinishCount().compareTo(current.getOrderCount()) > 0){
                    errorList.add(current);
                    current.setType(String.format("%s工序订单数量%d大于总数量%d或完成数量%d", current.getPhaseCode(), current.getOrderCount(), current.getTotalCount(), current.getFinishCount()));

                }
            }
        }

        for (TestValidCount testValidCount : errorList) {
            System.out.println(testValidCount.getApsWorkOrderId() + ":" + testValidCount.getType());
        }


    }

    public List<Order> orderList() {
        return orderMapper.lambdaQuery().eq(Order::getOrderType, 1).list();
    }

    @SneakyThrows
    @Transactional
    public void phase() {



        List<String> strings = FileUtils.readLines(new File("d:/1.txt"), "UTF-8");
        // 循环strings
        for (String string : strings) {
            // string按\t分割，并且用Arrays.toString()打印
            System.out.println(Arrays.toString(string.split("\t")));

            String[] split = string.split("\t");
            Phase phase = new Phase();
            phase.setMyCode(split[0].trim());
            phase.setName(split[1]);
            phase.setRemark(split[2]);
            phase.setInstr(split[3]);
            phase.setWorkFlowTime(toNum(split[4]));
            phase.setFlowTimeType(toNum(split[5]));
            phase.setFlowTimeValue(split[6]);
            phase.setFlowTimeUnit(toNum(split[7]));
            phase.setMinFlowTimeType(toNum(split[8]));
            phase.setMinFlowTimeValue(split[9]);
            phase.setMinFlowTimeUnit(toNum(split[10]));
            phase.setWorkloadShow(toNum(split[11]));
            phase.setFinishType(toNum(split[12]));
            Phase one = phaseMapper.lambdaQuery().eq(Phase::getMyCode, phase.getMyCode()).one();
            if(one == null){
                continue;
            }
            if(one.getId() > 85){
                continue;
            }
            MkBeanUtils.copyPropertiesIgnore(phase, one, "myCode", "name");
            phaseMapper.updateById(one);



        }

    }

    public Integer toNum(String str ){
        return StringUtils.hasText(str)? Integer.parseInt(str): null;
    }

    @SneakyThrows
    @Transactional
    public void phaseJob() {
        List<String> lines = FileUtils.readLines(new File("d:/2.txt"), "UTF-8");
        // 循环strings
        List<PhaseJobRef> collect = lines.stream()
                .map(e -> {
                    String[] split = e.split("\t");
                    PhaseJobRef phaseJobRef = new PhaseJobRef();

                    Phase one = phaseMapper.lambdaQuery().eq(Phase::getMyCode, split[0]).one();
                    phaseJobRef.setPhaseId(one.getId());

                    PhaseJob phaseJob = phaseJobMapper.lambdaQuery().eq(PhaseJob::getName, split[1]).one();
                    phaseJobRef.setPhaseJobId(phaseJob.getId());

                    phaseJobRef.setSeq(Integer.parseInt(split[2]));
                    return phaseJobRef;
                })
                .collect(Collectors.toList());

        Map<Integer, List<PhaseJobRef>> collect1 = collect.stream().collect(Collectors.groupingBy(PhaseJobRef::getPhaseId));
        for (Integer id : collect1.keySet()) {
            List<PhaseJobRef> values = collect1.get(id);
            values.sort(Comparator.comparing(PhaseJobRef::getSeq));
            for (int i = 0; i < values.size(); i++) {
                PhaseJobRef phaseJobRef = values.get(i);
                phaseJobRef.setSeq(i+1);
                phaseJobRefMapper.insert(phaseJobRef);
            }

        }


    }

    @Transactional
    public void phaseFix() {
        List<Phase> phaseList = phaseMapper.lambdaQuery().list();
        Map<Integer, Integer> map = new HashMap<>();
        map.put(1, 2);
        map.put(2, 1);
        map.put(3, 5);

        for (Phase phase : phaseList) {
            phase.setFlowTimeUnit(map.get(phase.getFlowTimeUnit()));
            phase.setMinFlowTimeUnit(map.get(phase.getMinFlowTimeUnit()));
            phaseMapper.updateById(phase);
        }

    }

    @SneakyThrows
    @Transactional
    public void phaseType() {

        List<String> lines = FileUtils.readLines(new File("d:/4.txt"), "UTF-8");
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        map.put(2, 2);
        map.put(3, 3);
        map.put(4, 4);
        map.put(6, 5);
        map.put(7, 6);
        map.put(8, 7);

        for (String line : lines) {
            String[] split = line.split("\t");
            phaseMapper.lambdaUpdate()
                    .set(Phase::getType, map.get(toNum(split[1])))
                    .eq(Phase::getMyCode, split[0])
                    .update();


        }

    }

    public void modifyTest() {
        NestSpace nestSpace = nestSpaceMapper.selectById(4);
        nestSpace.setTexture(null);
        nestSpaceMapper.updateById(nestSpace);

        nestSpaceMapper.lambdaUpdate().eq(NestSpace::getId, 5).set(NestSpace::getTexture, null).update();
    }

    public BaseResVo deletePickIng(BaseIdReqVo reqVo) {
        Order order = orderMapper.selectById(reqVo.getId());
        List<ApsWorkOrder> apsWorkOrderList = apsWorkOrderMapper.lambdaQuery()
                .eq(ApsWorkOrder::getOrderId, order.getId())
                .eq(ApsWorkOrder::getWorkChain, "WL")
                .isNotNull(ApsWorkOrder::getPickCode)
                .list();
        List<MesPicking> pickList = new ArrayList<>();
        if (CollUtil.isNotEmpty(apsWorkOrderList)) {
            MesPicking picking = new MesPicking();
            ApsWorkOrder apsWorkOrder = apsWorkOrderList.get(0);
            picking.setPickListNo(Long.valueOf(apsWorkOrder.getPickCode()));
            pickList.add(picking);
        }
        Result result = wmsLtkApiClient.deletePickIng(pickList);
        return BaseResVo.ok(result.getMessage());
    }


    /*@Transactional
    public void fixWl(Integer orderId, List<WmsPartProcurementReqDto> wmsReqDto) {
        Order o = orderMapper.selectById(orderId);

        List<ApsOrder> apsOrderList = apsOrderMapper.lambdaQuery().eq(ApsOrder::getOrderId, orderId).list();
        Map<Integer, ApsOrder> apsOrderMap = apsOrderList.stream().collect(Collectors.toMap(BaseEntity::getId, e -> e));

        List<ApsWorkOrder> apsWorkOrderList = apsWorkOrderMapper.lambdaQuery()
//                .eq(ApsWorkOrder::getWorkChain, "WL")
//                .eq(ApsWorkOrder::getMaterType, "Component")
                .eq(ApsWorkOrder::getOrderId, orderId)
                .list();


        Map<Integer, ApsWorkOrder> workOrderMap = apsWorkOrderList.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));



        Map<String, Map<String, Map<String, WmsPartProcurementReqDto>>> collect = wmsReqDto.stream().collect(Collectors.groupingBy(WmsPartProcurementReqDto::getWpxNo, Collectors.groupingBy(WmsPartProcurementReqDto::getRootPlmid, Collectors.toMap(WmsPartProcurementReqDto::getMaterialCode, e -> e))));


        List<ApsWorkOrder> apsWorkOrderList1 = apsWorkOrderList.stream().filter(e -> e.getWorkChain().equals("WL")).collect(Collectors.toList());

        for (ApsWorkOrder apsWorkOrder : apsWorkOrderList1) {

            String gen = PkgUtils.gen(apsOrderMap.get(apsWorkOrder.getApsOrderId()).getSeq());
            Map<String, Map<String, WmsPartProcurementReqDto>> stringMapMap = collect.get(gen);
            if(stringMapMap == null){
                throw SyExceptionUtils.e("没有找到该包:{}", gen);
            }

            ApsWorkOrder apsWorkOrder1 = workOrderMap.get(apsWorkOrder.getPid());

            Map<String, WmsPartProcurementReqDto> stringWmsPartProcurementReqDtoMap = stringMapMap.get(apsWorkOrder1.getPlmId());
            if(stringWmsPartProcurementReqDtoMap == null){
                throw SyExceptionUtils.e("没有找到父级:{}", apsWorkOrder1.getPlmId());
            }

            WmsPartProcurementReqDto wmsPartProcurementReqDto = stringWmsPartProcurementReqDtoMap.get(apsWorkOrder.getPlmId());
            if(wmsPartProcurementReqDto == null){
                throw SyExceptionUtils.e("没有找到该件:{}", apsWorkOrder.getPlmId());
            }

            apsWorkOrderMapper.lambdaUpdate()
                    .set(ApsWorkOrder::getPickCode, wmsPartProcurementReqDto.getPickListNo())
                    .set(ApsWorkOrder::getPickSeq, wmsPartProcurementReqDto.getPickListItemNo())
                    .eq(ApsWorkOrder::getId, apsWorkOrder.getId())
                    .update();

        }

        wmsApiClient.partProcurement(wmsReqDto, orderId);



    }

     */

    @Transactional
    public void falsifyingData(FalsifyingDataReqVo reqVo) {

        List<Order> orderList = orderMapper.lambdaQuery().eq(Order::getConstructNo, reqVo.getConstructCode()).list();

        if (CollUtil.isEmpty(orderList)) {
            return;
        }

        List<ApsWorkOrder> workOrderList = apsWorkOrderMapper.lambdaQuery()
                .eq(ApsWorkOrder::getPlmId, reqVo.getPlmId())
                .in(ApsWorkOrder::getOrderId, orderList.stream().map(BaseEntity::getId).collect(Collectors.toList()))
                .list();

        if(CollUtil.isEmpty(workOrderList)){
            return ;
        }

        Map<Integer, Order> orderMap = orderList.stream().collect(Collectors.toMap(e -> e.getId(), e -> e));

        if (workOrderList.get(0).getMaterType().equals("Assembly")) {
            for (ApsWorkOrder workOrder : workOrderList) {

                workOrder.setFinishCount(BigDecimal.ZERO);
                workOrder.setStatus(3);
                apsWorkOrderMapper.updateById(workOrder);

                List<ApsWorkDetail> workDetailList = apsWorkDetailMapper.lambdaQuery().eq(ApsWorkDetail::getApsWorkOrderId, workOrder.getId()).list();

                if(CollUtil.isEmpty(workDetailList)){
                    continue;
                }

                List<String> phaseList = Arrays.asList("PD", "PZ", "XH");
                List<ApsWorkDetail> detailList = workDetailList.stream().filter(e -> phaseList.contains(e.getPhaseCode())).sorted(Comparator.comparing(ApsWorkDetail::getId).reversed()).collect(Collectors.toList());

                for (ApsWorkDetail detail : detailList) {
                    detail.setFinishCount(BigDecimal.ZERO);
                    detail.setStatus(3);
                    apsWorkDetailMapper.updateById(detail);

                }
                for (ApsWorkDetail detail : detailList) {
                    apsWorkDetailMapper.lambdaUpdate()
                            .set(ApsWorkDetail::getUniqueCode, null)
                            .eq(ApsWorkDetail::getId, detail.getId())
                            .update();
                }

                List<ApsWorkDetail> detailList1 = workDetailList.stream().filter(e -> !phaseList.contains(e.getPhaseCode())).sorted(Comparator.comparing(ApsWorkDetail::getId).reversed()).collect(Collectors.toList());
                for (ApsWorkDetail detail : detailList1) {
                    apsWorkDetailMapper.lambdaUpdate()
                            .set(ApsWorkDetail::getUniqueCode, null)
                            .eq(ApsWorkDetail::getId, detail.getId())
                            .update();
                }


                List<Integer> collect = workDetailList.stream().map(BaseEntity::getId).collect(Collectors.toList());
                for (ApsWorkDetail apsWorkDetail : workDetailList) {
                    workDetailTaskMapper.deleteByWorkDetailId(apsWorkDetail.getId());
                }
                List<WorkDetailTask> taskList = workDetailTaskMapper.lambdaQuery().in(WorkDetailTask::getApsWorkDetailId, workDetailList.stream().map(BaseEntity::getId).collect(Collectors.toList())).list();
                for (WorkDetailTask workDetailTask : taskList) {
                    workDetailTask.setFinishCount(0);
                    workDetailTask.setStatus(2);
                    workDetailTaskMapper.updateById(workDetailTask);
                }

                Order order = orderMap.get(workOrder.getOrderId());

                List<ApsWorkOrder> children = apsWorkOrderMapper.lambdaQuery().eq(ApsWorkOrder::getPid, workOrder.getId()).list();
                for (ApsWorkOrder child : children) {
                    Part part = partMapper.lambdaQuery().eq(Part::getPlmId, child.getPlmId()).eq(Part::getConstructNo, order.getConstructNo()).eq(Part::getPhaseCode, "KJ").one();

                    if(part == null){
                        part = new Part();
                        part.setPlmId(child.getPlmId());
                        part.setPhaseCode("KJ");
                        part.setPhaseName("库检");
                        part.setConstructNo(order.getConstructNo());
                        part.setPartType(2);
                        part.setPartCount(100 * child.getPartCount().intValue());
                        part.setFailCount(0);
                        part.setDamageCount(0);
                        partMapper.insert(part);
                    } else {
                        part.setPartCount(100 * child.getPartCount().intValue());
                        partMapper.updateById(part);
                    }
                }


            }
        } else if (workOrderList.get(0).getMaterType().equals("Platepart")) {
            for (ApsWorkOrder workOrder : workOrderList) {

                workOrder.setFinishCount(BigDecimal.ZERO);
                workOrder.setStatus(3);
                apsWorkOrderMapper.updateById(workOrder);

                List<ApsWorkDetail> workDetailList = apsWorkDetailMapper.lambdaQuery().eq(ApsWorkDetail::getApsWorkOrderId, workOrder.getId()).list();

                if (CollUtil.isEmpty(workDetailList)) {
                    continue;
                }

                ApsWorkDetail apsWorkDetail = workDetailList.stream().filter(e -> !e.getPhaseCode().equals("KJ")).max(Comparator.comparing(ApsWorkDetail::getPhaseSeq)).get();
                List<ApsWorkDetail> collect = workDetailList.stream().filter(e -> e.getPhaseSeq() >= apsWorkDetail.getPhaseSeq()).collect(Collectors.toList());
                for (ApsWorkDetail workDetail : collect) {
                    workDetail.setFinishCount(BigDecimal.ZERO);
                    workDetail.setStatus(3);
                    apsWorkDetailMapper.updateById(workDetail);
                    List<WorkDetailTask> taskList = workDetailTaskMapper.lambdaQuery().eq(WorkDetailTask::getApsWorkDetailId, workDetail.getId()).list();
                    for (WorkDetailTask workDetailTask : taskList) {
                        workDetailTask.setFinishCount(0);
                        workDetailTask.setStatus(2);
                        workDetailTaskMapper.updateById(workDetailTask);
                    }
                }

                Order order = orderMap.get(workOrder.getOrderId());

                Part part = partMapper.lambdaQuery().eq(Part::getPlmId, workOrder.getPlmId()).eq(Part::getConstructNo, order.getConstructNo()).eq(Part::getPhaseCode, apsWorkDetail.getPhaseCode()).one();

                if(part == null){
                    part = new Part();
                    part.setPlmId(workOrder.getPlmId());
                    part.setPhaseCode(apsWorkDetail.getPhaseCode());
                    part.setPhaseName(apsWorkDetail.getPhaseName());
                    part.setConstructNo(order.getConstructNo());
                    part.setPartType(2);
                    part.setPartCount(reqVo.getTotal() * workOrder.getPartCount().intValue());
                    part.setFailCount(0);
                    part.setDamageCount(0);
                    partMapper.insert(part);
                } else {
                    part.setPartCount(reqVo.getTotal() * workOrder.getPartCount().intValue());
                    partMapper.updateById(part);
                }

            }

        } else if (workOrderList.get(0).getMaterType().equals("Component")) {
            throw SyExceptionUtils.e("请选择正确的工单类型!");
        }

    }

    public void unlockDeleteNest(BaseIdReqVo reqVo) throws InterruptedException {
        List<SinoCamReceiveNestPart> nestPartList = sinoCamReceiveNestPartMapper.lambdaQuery().eq(SinoCamReceiveNestPart::getOrderId, reqVo.getId()).list();
        List<SinoCamReceiveNestPlate> plateList = sinoCamReceiveNestPlateMapper.lambdaQuery().in(SinoCamReceiveNestPlate::getStockListNo, nestPartList.stream().map(SinoCamReceiveNestPart::getPlateCode).collect(Collectors.toList())).list();
        for (SinoCamReceiveNestPlate pl : plateList) {
            String p = pl.getStockListNo();
            UpdateNxolpstatusVo vo = new UpdateNxolpstatusVo();
            vo.setNxolnestixno(p);
            plateService.plateLock(vo);

            sinoCamService.clearNestResultInfoPlate(p);

            Thread.sleep(500);
        }
    }

    public void testTable() {
        List<NestReceiveNest> list1 = nestReceiveNestMapper.lambdaQuery().list();
        List<NestReceivePlate> list2 = nestReceivePlateMapper.lambdaQuery().list();
        List<NestReceivePart> list3 = nestReceivePartMapper.lambdaQuery().list();
        List<NestReceiveExcess> list4 = nestReceiveExcessMapper.lambdaQuery().list();
        List<NestReceiveMove> list5 = nestReceiveMoveMapper.lambdaQuery().list();
    }

    public void ptReport() {
        List<ApsWorkDetail> apsWorkDetailList = apsWorkDetailMapper.lambdaQuery()
                .eq(ApsWorkDetail::getOrderId, 997)
                .eq(ApsWorkDetail::getPhaseCode, "PT")
                .ne(ApsWorkDetail::getStatus, 4)
                .list();

        for (ApsWorkDetail detail : apsWorkDetailList) {
             WorkDetailTask task = new WorkDetailTask();
             task.setApsWorkDetailId(detail.getId());
             task.setFinishCount(0);
             task.setFailCount(0);
             task.setGroupCode("4-3_PTX_00");
             task.setPlmid(detail.getPlmId());
             task.setPhaseCode("PT");
             task.setStatus(2);
             task.setTotalCount(1);
             task.setActualStartDateTime(LocalDateTime.now());
             task.setActualEndDateTime(LocalDateTime.now());
             task.setMaterCode(detail.getPlmId());
             task.setMaterName(detail.getMaterName());
             task.setPhaseName(detail.getPhaseName());
             task.setPrePhaseCode("FJ");
             task.setPartPath("http://172.31.3.55:81/png/master/ZHENGZHOU/archive/emf/29/62429.png");
             task.setOrderCode("J25-170-069");
             task.setPlanStartDateTime(detail.getPlanStartDateTime());
             task.setPlanEndDateTime(detail.getPlanEndDateTime());
             task.setWeight(BigDecimal.valueOf(29));
             task.setNestPlateId(31717);
             task.setType(2);
             task.setNestId("J25-170-069_007.cld");
             task.setPlateCode("50_006_AG_25_08993");
             task.setLength(BigDecimal.valueOf(745));
             task.setWidth(BigDecimal.valueOf(810));
             workDetailTaskMapper.insert(task);
        }
    }

    public void testCount() {
        ApsWorkOrder workOrder = apsWorkOrderMapper.selectById(130964);
        int i = 0;
        if (workOrder.getPickSeq() == null) {
            i = workOrder.getOrderCount().intValue();
        } else {
            i = workOrder.getOrderCount().intValue() - workOrder.getPickSeq();
        }
        log.info("数量为：{}", i);
    }

    public void deleteLanNest(String nestCode) {

        List<NestReceivePlate> plateList = nestReceivePlateMapper.lambdaQuery().eq(NestReceivePlate::getNestCode, nestCode).list();
        for (NestReceivePlate plate : plateList) {
            String plateCode = plate.getPlateCode();

            // 先删除钢板上的零件信息
            List<NestReceivePart> nestPartList = nestReceivePartMapper.lambdaQuery().eq(NestReceivePart::getPlateCode, plateCode).list();

            WorkDetailTask yCTask = workDetailTaskMapper.lambdaQuery()
                    .eq(WorkDetailTask::getPlmid, plateCode)
                    .eq(WorkDetailTask::getType, 1)
                    .eq(WorkDetailTask::getPhaseCode, WorkshopProp.YC_PHASE_CODE)
                    .one();
            if (!ObjectUtils.isEmpty(yCTask) && yCTask.getStatus() == 3) {
                for (NestReceivePart nestPart : nestPartList) {
                    ApsWorkDetail qgApsWorkDetail = apsWorkDetailMapper.lambdaQuery()
                            .eq(ApsWorkDetail::getId, nestPart.getPlanId())
                            .one();
                    if (!ObjectUtils.isEmpty(qgApsWorkDetail)) {
                        ApsWorkDetail ycWorkDetail = apsWorkDetailMapper.lambdaQuery().eq(ApsWorkDetail::getType, 2)
                                .eq(ApsWorkDetail::getApsWorkOrderId, qgApsWorkDetail.getApsWorkOrderId())
                                .eq(ApsWorkDetail::getPhaseCode, WorkshopProp.YC_PHASE_CODE).last(" LIMIT 1 ").one();

                        if (!ObjectUtils.isEmpty(ycWorkDetail)) {
                            apsWorkDetailMapper.lambdaUpdate().eq(ApsWorkDetail::getId, ycWorkDetail.getId())
                                    .set(ycWorkDetail.getFinishCount().subtract(new BigDecimal(nestPart.getTotalCount())).compareTo(ycWorkDetail.getTotalCount()) < 0, ApsWorkDetail::getStatus, 3)
                                    .setSql("finish_count=finish_count-" + nestPart.getTotalCount()).update();
                        }
                    }

                }

            }
            //删除报工记录
            List<WorkRecord> recordList = workRecordMapper.lambdaQuery().eq(WorkRecord::getPalletNumber, plateCode).eq(WorkRecord::getType, 2)
                    .eq(WorkRecord::getPhaseCode, WorkshopProp.YC_PHASE_CODE).list();
            for (WorkRecord r : recordList) {
                workRecordMapper.deleteWithId(r.getId());
            }

            WorkDetailTask llTask = workDetailTaskMapper.lambdaQuery()
                    .eq(WorkDetailTask::getPlmid, plateCode)
                    .eq(WorkDetailTask::getType, 1)
                    .eq(WorkDetailTask::getPhaseCode, WorkshopProp.LL_PHASE_CODE)
                    .one();
            if (!ObjectUtils.isEmpty(llTask) && llTask.getStatus() == 3) {
                for (NestReceivePart nestPart : nestPartList) {
                    ApsWorkDetail qgWrkDetail = apsWorkDetailMapper.lambdaQuery().eq(ApsWorkDetail::getId, nestPart.getPlanId()).one();
                    ApsWorkDetail llApsWorkDetail = apsWorkDetailMapper.lambdaQuery().eq(ApsWorkDetail::getApsWorkOrderId, qgWrkDetail.getApsWorkOrderId())
                            .eq(ApsWorkDetail::getType, 2).eq(ApsWorkDetail::getPhaseCode, WorkshopProp.LL_PHASE_CODE).last("  LIMIT 1 ").one();
                    if (!org.apache.commons.lang3.ObjectUtils.isEmpty(llApsWorkDetail)) {
                        //更新零件的计划信息
                        apsWorkDetailMapper.lambdaUpdate().eq(ApsWorkDetail::getId, llApsWorkDetail.getId())
                                .set(llApsWorkDetail.getFinishCount().subtract(new BigDecimal(nestPart.getTotalCount())).compareTo(llApsWorkDetail.getTotalCount()) < 0, ApsWorkDetail::getStatus, 3)
                                .setSql("finish_count=finish_count-" + nestPart.getTotalCount()).update();
                    }
                }
            }

            if (CollUtil.isNotEmpty(nestPartList)) {
                List<SinoCamPushPlan> pushPlanList = sinoCamPushPlanMapper.lambdaQuery()
                        .in(SinoCamPushPlan::getNestPlanId, nestPartList.stream().map(NestReceivePart::getPlanId).collect(Collectors.toList())).list();
                Map<String, SinoCamPushPlan> pushPlanMap = pushPlanList.stream().collect(Collectors.toMap(SinoCamPushPlan::getNestPlanId, Function.identity()));

                for (NestReceivePart part : nestPartList) {
                    SinoCamPushPlan pp = pushPlanMap.get(String.valueOf(part.getPlanId()));
                    pp.setPlanFinishAmount(pp.getPlanFinishAmount().subtract(BigDecimal.valueOf(part.getTotalCount())));
                    pp.setConsumeStatus(0);
                    sinoCamPushPlanMapper.updateById(pp);
                }
                for (NestReceivePart a : nestPartList) {
                    nestReceivePartMapper.deleteWithId(a.getId());
                }
            }

            nestReceivePlateMapper.deleteMesNestWithCode(plateCode);

            apsWorkDetailMapper.deleteMesNestWithCode(plateCode);

            platePhaseMapper.deleteMesNestWithCode(plateCode);

            nestReceiveExcessMapper.deleteMesNestWithCode(plateCode);

            plateMapper.deleteMesNestWithCode(plateCode);

            wmsPlatePickMapper.deleteMesNestWithCode(plateCode);

            workDetailTaskMapper.deleteMesNestWithCode(plateCode);

            nestReceiveMoveMapper.deleteMesNestWithCode(nestCode);

            nestReceiveNestMapper.deleteMesNestWithCode(nestCode);

        }

    }

    public void sendMsgFlyBook(String userCode, String title, String msg) {

//        DictType personBind = dictTypeMapper.lambdaQuery().eq(DictType::getDictCode, "nestMsgPush").one();
//        List<DictData> personBindList = dictDataMapper.lambdaQuery().eq(DictData::getDictType, personBind.getId()).list();
        List<String> collect = Arrays.asList(userCode.split(","));
        for (String s : collect) {
            SendCardMsgDto dto = new SendCardMsgDto();
            dto.setReceive_id(s);
            dto.setTitle(title);
            dto.setContent(msg);
            dto.setTemplate_type("1");
            log.info("发送到飞书的消息：{}", JsonUtils.toJsonString(dto));
//            Result result = momAndonFeign.sendCardMsg(dto);
            SendApsMsgDto dto1 = new SendApsMsgDto();
            dto1.setUuid(UUID.randomUUID().toString());
            dto1.setReceiveId(s);
//            PlaceHolderUtils.getPlaceHolder(ApsConstant.FEISHU_MSG)

            String replace = PlaceHolderUtils.replace(ApsConstant.FEISHU_MSG, new HashMap<String, String >() {{
                put("title", title);
                put("content", msg);
            }});
            dto1.setContent(replace);
            Result result = momAndonFeign.sendApsMsg(dto1);

            log.info("发送到飞书的响应：{}", JsonUtils.toJsonString(result));
        }

    }

    @Transactional
    public Page<Order> table(TestTableReqVo reqVo) {

        Map<String, String> mapping = new HashMap<>();
        mapping.put("orderDateTime", "o.order_date_time");
        mapping.put("orderCount", "o.order_qty");
        mapping.put("materCode", "o.mater_code");


        QueryWrapper<Object> query = Wrappers.query();
        for (SearchParam searchParam : reqVo.getSearchParams()) {
            if (searchParam.getType().equals("date:single")) {
                query.eq("DATE(" + mapping.get(searchParam.getKey()) + ")", searchParam.getValue());
            } else if (searchParam.getType().equals("date:multiple")) {
                query.in("DATE(" + mapping.get(searchParam.getKey()) + ")", Arrays.asList(searchParam.getValue().split(",")));
            } else if (searchParam.getType().equals("date:range")) {
                List<String> date = Arrays.asList(searchParam.getValue().split(","));
                date.sort(String::compareTo);
                query.ge("DATE(" + mapping.get(searchParam.getKey()) + ")", date.get(0));
                query.le("DATE(" + mapping.get(searchParam.getKey()) + ")", date.get(1));
            } else if (searchParam.getType().equals("number:eq")) {
                query.eq(mapping.get(searchParam.getKey()), Integer.valueOf(searchParam.getValue()));
            } else if (searchParam.getType().equals("number:ne")) {
                query.ne(mapping.get(searchParam.getKey()), Integer.valueOf(searchParam.getValue()));
            } else if (searchParam.getType().equals("number:gt")) {
                query.gt(mapping.get(searchParam.getKey()), Integer.valueOf(searchParam.getValue()));
            } else if (searchParam.getType().equals("number:ge")) {
                query.ge(mapping.get(searchParam.getKey()), Integer.valueOf(searchParam.getValue()));
            } else if (searchParam.getType().equals("number:lt")) {
                query.lt(mapping.get(searchParam.getKey()), Integer.valueOf(searchParam.getValue()));
            } else if (searchParam.getType().equals("number:le")) {
                query.le(mapping.get(searchParam.getKey()), Integer.valueOf(searchParam.getValue()));
            } else if (searchParam.getType().equals("number:between")) {
                List<Integer> date = Arrays.stream(searchParam.getValue().split(",")).map(Integer::valueOf).sorted().collect(Collectors.toList());
                query.ge(mapping.get(searchParam.getKey()), date.get(0));
                query.le(mapping.get(searchParam.getKey()), date.get(1));
            } else if (searchParam.getType().equals("number:notBetween")) {
                List<Integer> date = Arrays.stream(searchParam.getValue().split(",")).map(Integer::valueOf).sorted().collect(Collectors.toList());
                query.and(queryWrapper ->{
                    queryWrapper.lt(mapping.get(searchParam.getKey()), date.get(0));
                    queryWrapper.or();
                    queryWrapper.gt(mapping.get(searchParam.getKey()), date.get(1));
                });

            } else if (searchParam.getType().equals("string:eq")) {
                query.eq(mapping.get(searchParam.getKey()), searchParam.getValue());
            } else if (searchParam.getType().equals("string:ne")) {
                query.ne(mapping.get(searchParam.getKey()), searchParam.getValue());
            } else if (searchParam.getType().equals("string:like")) {
                query.like(mapping.get(searchParam.getKey()), searchParam.getValue());
            } else if (searchParam.getType().equals("string:notLike")) {
                query.notLike(mapping.get(searchParam.getKey()), searchParam.getValue());
            } else if (searchParam.getType().equals("string:startWith")) {
                query.likeRight(mapping.get(searchParam.getKey()), searchParam.getValue());
            } else if (searchParam.getType().equals("string:endWith")) {
                query.likeLeft(mapping.get(searchParam.getKey()), searchParam.getValue());
            }


        }

//        Page<OrderBom> awdList = apsWorkDetailMapper.testTable(query, reqVo.toPage());

        Page<Order> awdList = apsWorkDetailMapper.testTable(query, reqVo.toPage());
        return awdList;
//        System.out.println(awdList);
    }
}

